package com.example.demo.util;

import com.example.demo.service.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

//标注该类为配置类
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    MyUserDetailService userDetailService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService).passwordEncoder(encoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //设置自己的登录页面
        http.authorizeRequests()
                .antMatchers("/index","/information","/SelectCourse","/displaySelect")
                .access("hasRole('ROLE_USER')")
                .antMatchers("/","/register","/welcome")
                .permitAll()
                .and()
                .csrf()
                .disable()
            .formLogin()
                .loginPage("/")
                .loginProcessingUrl("/index")
                .successForwardUrl("/index")
            .and()
                .logout()
                .logoutSuccessUrl("/");
    }

    //将密码加密器加载进项目中
    @Bean
    public PasswordEncoder encoder(){
        return new BCryptPasswordEncoder();
    }
}
